package controllers;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.*;

import org.apache.jasper.tagplugins.jstl.core.Redirect;

import models.Area;
import models.Benefit;
import models.Customer;
import models.SolutionSubmission;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

@SuppressWarnings("serial")
public class AddBenefitServlet extends HttpServlet {
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/xml");

		Date today = new java.util.Date();
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		String user_email = user.getEmail().toLowerCase();
		String benefitName = String.valueOf(req.getParameter("BenefitName"));
		
		String id = String.valueOf(req.getParameter("id"));
		String Action = String.valueOf(req.getParameter("Action"));
		
		
		Objectify ofy = ObjectifyService.begin();
		int lastIndex = Integer.parseInt("0");
		
		try {
			
			
			
			if (Action.toUpperCase().trim().equalsIgnoreCase("UPDATE"))
			{
				Benefit edititem = ofy.get(Benefit.class,Long.parseLong(id));
				edititem.setBenefitName(benefitName);
				edititem.setSubmittedBY(user_email);
				edititem.setSubmittedON(today);
				ofy.put(edititem);

			}
			else
			{
				Query<Benefit> qCount = ofy.query(Benefit.class).order("-benefitIndex");
				if (qCount.countAll() > 0)
				{
					for ( Benefit f : qCount.fetch() ) {
						lastIndex =f.getBenefitIndex();
						break;
					}
				}
				Query<Benefit> q = ofy.query(Benefit.class).filter("benefitName",benefitName);
				if (q.countAll() <= 0) {
					Benefit newitems = new Benefit();
					newitems.setBenefitIndex(lastIndex +1);
					newitems.setBenefitName(benefitName);
					newitems.setSubmittedBY(user_email);
					newitems.setSubmittedON(today);
					ofy.put(newitems);
				}
			}
			
		
			resp.sendRedirect("/modules/admin/benefit-admin.jsp");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
} // Class End
